package com.example.web.websystem.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;

/**
 * Created by YangGang on 2021/3/8 17:57。
 */
public class CookieUtil {
    //默认有效时间（秒）
    private static int DEFAULT_MAX_AGE = 3600 * 6;

    public static Cookie getCookie(HttpServletRequest request, String cookieName) {
        Cookie[] cookies = request.getCookies();
        Cookie cookie = null;
        try {
            cookie = Arrays.stream(cookies).filter(c -> cookieName.equals(c.getName())).findFirst().get();
        } catch (Exception e) {
            //e.printStackTrace();
        }
        return cookie;
    }

    public static String getCookieValue(HttpServletRequest request, String cookieName) {
        Cookie[] cookies = request.getCookies();
        String value = null;
        try {
            value = Arrays.stream(cookies).filter(c -> cookieName.equals(c.getName())).findFirst().get().getValue();
        } catch (Exception e) {
            //e.printStackTrace();
        }
        return value;
    }

    public static void updateCookie(HttpServletResponse response, Cookie cookie) {
        response.addCookie(cookie);
    }

    public static void updateCookieValue(HttpServletResponse response, String name, String value) {
        Cookie cookie = new Cookie(name, value);
        cookie.setMaxAge(DEFAULT_MAX_AGE);
        cookie.setPath("/");
        response.addCookie(cookie);
    }

    public static void removeCookie(HttpServletResponse response, String name) {
        Cookie cookie = new Cookie(name, null);
        cookie.setMaxAge(0);
        response.addCookie(cookie);
    }

    public static Cookie removeCookie(HttpServletResponse response, Cookie cookie) {
        cookie.setMaxAge(0);
        response.addCookie(cookie);
        return cookie;
    }


}
